<template>
	<view>
		<u-upload class="" uploadIcon="plus" :disabled="disabled" :maxCount="limit" :width="width" accept="video"
			:capture="capture" :height="height" :fileList="images" :compressed="false" :deletable="!disabled" @afterRead="afterRead"
			@delete="deletePic" :previewImage="false" v-if="!images.length">
			<view :style="{'width':width,'height':height}">
				<slot></slot>
			</view>
		</u-upload>
		<view class="" v-if="images.length">
			<view class="video-item" v-for="(item,index) in images" :key="item.url"
				:style="{'width':width,'height':height}">
				<view class="video full-width full-height" @click="handlePrevideo(item)">
					<image :src="item.url + '?x-oss-process=video/snapshot,t_0,f_jpg'" class="full-width"
						mode="widthFix"></image>
					<image src="/static/images/index/video.png" class="width-50 height-50 video-play" mode="widthFix">
					</image>
					<image src="/static/upload-delete.png" class="width-20 height-20 video-item-delete" mode=""
						@click.stop="deletePic({index})"></image>
				</view>
			</view>
		</view>
		<u-overlay :show="overlayShow" @click="overlayShow = false">
			<view class="full-width full-height ">
				<video :src="prevideo" class="full-width full-height relative flex justify-end" :direction="0" autoplay auto-pause-if-navigate @play="playVedio"
					@fullscreenchange="screenchange" :show-fullscreen-btn="false" id="video">
						<cover-image src="/static/images/order/close-2.png" class="width-30 height-30 absolute" style="top:60px;left:calc(100% - 40px);" @click.stop="overlayShow = false"></cover-image>
				</video>
			</view>
		</u-overlay>
		<Toast></Toast>
	</view>
</template>

<script>
	import upload from '@/utils/upload';
	export default {
		name: 'upload-video',
		options: {
			styleIsolation: 'shared' // 解除样式隔离
		},
		props: {
			disabled: {
				type: Boolean,
				default: false
			},
			value: {
				type: [String, Array],
				default: ''
			},
			// 文件类型, 例如['png', 'jpg', 'jpeg']
			fileType: {
				type: Array,
				default: () => ['mp4']
			},
			// 大小限制(MB)
			fileSize: {
				type: Number,
				default: 30
			},
			// 视频数量
			limit: {
				type: Number,
				default: 1
			},
			capture: {
				type: [Array, String],
				default: () => ['album', 'camera']
			},
			width: {
				type: [Number, String],
				default: '66px'
			},
			height: {
				type: [Number, String],
				default: '66px'
			}
		},
		data() {
			return {
				overlayShow: false,
				prevideo: '',
				assetsPath: getApp().globalData.config.assetsPath,
				images: [],
				uploadList: []
			};
		},
		watch: {
			value: {
				handler(val) {
					if (val) {
						// 首先将值转为数组
						const list = Array.isArray(val) ? val : val.split(',');
						this.uploadList = list;
						// 然后将数组转为对象数组
						this.images = list.map(item => {
							item = item.includes(this.assetsPath) ? item.replace(this.assetsPath, '') :
								item;
							if (typeof item === 'string') {
								item = {
									name: this.assetsPath + item,
									url: this.assetsPath + item,
									status: 'success'
								};
							}
							return item;
						});
					} else {
						this.images = [];
						this.uploadList = [];
						return [];
					}
				},
				deep: true,
				immediate: true
			},
			uploadList: {
				handler(val) {
					this.$emit('input', val.toString());
				}
			}
		},
		methods: {
			playVedio() {
				// uni.createVideoContext('video', this).requestFullScreen();
				// screen.orientation.lock('landscape');
			},
			screenchange(e) {
				if (!e.detail.fullScreen) { // 退出全屏，锁定竖屏
					plus.screen.lockOrientation('portrait-primary');
					plus.screen.orientation.lock('landscape');
				}

			},
			handlePrevideo(item) {

				this.prevideo = item.url
				this.overlayShow = true
			},
			// 删除视频
			deletePic(event) {
				this.uploadList.splice(event.index, 1);
				this.images.splice(event.index, 1);
			},
			// 选择视频
			async afterRead(event) {
				const {
					file
				} = event;
				if (!this.uploadFileValidate(file)) return false;
				this.$modal.loading('正在上传视频');
				this.images.push({
					...file,
					status: 'uploading',
					message: '上传中'
				});
				this.uploadFilePromise(file.url);
			},
			// 校验文件
			uploadFileValidate(file) {
				let isImg = false;
				if (this.fileType.length) {
					let fileExtension = '';
					let fileUrl = file.name ? file.name : file.url;
					if (fileUrl.lastIndexOf('.') > -1) {
						fileExtension = fileUrl.slice(fileUrl.lastIndexOf('.') + 1);
						// 文件类型转换为小写 兼容IOS
						fileExtension = fileExtension.toLowerCase();
					}
					isImg = this.fileType.some(type => {
						if (file.type.indexOf(type) > -1) return true;
						if (fileExtension && fileExtension.indexOf(type) > -1) return true;
						return false;
					});
				} else {
					isImg = file.type.indexOf('video') > -1;
				}
				if (!isImg) {
					this.$toast(`文件格式不正确, 请上传${this.fileType.join('/')}视频格式文件!`)
					// this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join('/')}视频格式文件!`);
					return false;
				}
				if (this.fileSize) {
					const isLt = file.size / 1024 / 1024 < this.fileSize;
					if (!isLt) {
						// this.$modal.msgError(`上传的视频大小不能超过 ${this.fileSize} MB!`);
						this.$modal.msgError(`上传的视频过大！`);
						return false;
					}
				}
				return true;
			},
			// 上传视频
			uploadFilePromise(url) {
				let fileListLen = this.images.length - 1;
				upload({
						url: '/technicianapp/Index/uploadImage',
						filePath: url
					})
					.then(res => {
						console.log('video upload success: ',res);
						this.$modal.closeLoading();
						this.uploadFileSuccess(res.data.url, fileListLen);
					})
					.catch(err => {
						this.$modal.closeLoading();
						this.$modal.msgError('上传失败');
						this.deletePic({
							index: fileListLen
						});
					});
			},
			// 上传成功
			uploadFileSuccess(url, idx) {
				this.$set(this.images, idx, {
					status: 'success',
					message: '成功',
					url
				});
				this.uploadList.push(url);
			}
		}
	};
</script>
<style lang="scss" scoped>
	.video-item {
		position: relative;
		border-radius: 12rpx;
		overflow: hidden;

		.video {
			border-radius: 12rpx;
			overflow: hidden;
			background-color: #eee;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;

			.video-play {
				position: absolute;
				z-index: 99;
			}
		}

		::v-deep video {
			border-radius: 12rpx !important;
			overflow: hidden !important;
		}

		.video-item-bg {
			width: 100%;
			height: 100%;
			background-color: rgba(255, 255, 255, 0.4);
			z-index: 99;
			position: absolute;
			top: 0;
			right: 0;
			pointer-events: none;
			border-radius: 12rpx;
			overflow: hidden;
		}



		.video-item-delete {
			position: absolute;
			top: 0;
			right: 0;
			z-index: 99;
		}
	}

	::v-deep .u-upload {
		.u-upload__wrap {
			padding: -8px;

			.u-upload__wrap__preview,
			.u-upload__button {
				// margin: 8px 8px 8px 0;
			}

			.u-upload__deletable {
				height: 20px;
				width: 20px;

				.u-upload__deletable__icon {
					transform: scale(0.9);
					top: 10%;
					right: 10%;
				}
			}
		}
	}

	.display-none {
		display: none;
	}

	::v-deep .u-upload__button {
		margin: 0 !important;
	}
</style>